<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <div class="logo">
          <img src="@/assets/logo.png" alt="Logo" class="logo-img" />
          <h1 class="system-title">盼寻密友</h1>
        </div>
        <p class="welcome-text">欢迎回来，请登录您的账户</p>
      </div>
      
      <transition name="fade" mode="out-in">
        <div class="login-form" :key="formKey">
          <div class="form-group">
            <div class="input-wrapper">
              <i class="icon-user"></i>
              <input
                id="username"
                v-model="loginForm.username"
                class="login-input"
                type="text"
                placeholder="用户名或邮箱"
                @keyup.enter="handleLogin"
              />
            </div>
          </div>
          
          <div class="form-group">
            <div class="input-wrapper">
              <i class="icon-lock"></i>
              <input
                id="password"
                v-model="loginForm.password"
                class="login-input"
                type="password"
                placeholder="密码"
                @keyup.enter="handleLogin"
              />
            </div>
          </div>
          
          <div class="form-options">
            <div class="remember-me">
              <input
                id="remember"
                v-model="loginForm.remember"
                type="checkbox"
                class="checkbox"
              />
              <label for="remember" class="checkbox-label">记住我</label>
            </div>
            <a href="#" @click.prevent="handleForgotPassword" class="forgot-password">忘记密码？</a>
          </div>
          
          <button class="login-btn" @click="handleLogin" :disabled="isLoggingIn">
            <span v-if="!isLoggingIn" class="btn-text">登录</span>
            <span v-else class="btn-text">登录中...</span>
          </button>
          
          <div class="divider">
            <span class="divider-text">或</span>
          </div>
          
          <div class="social-login">
            <button class="social-btn google">
              <i class="icon-google"></i>
              <span>Google 登录</span>
            </button>
            <button class="social-btn github">
              <i class="icon-github"></i>
              <span>GitHub 登录</span>
            </button>
          </div>
          
          <div class="register-link">
            还没有账户？<a href="#" @click.prevent="handleRegister">立即注册</a>
          </div>
          
          <div v-if="errorMessage" class="error-message">
            {{ errorMessage }}
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
import { login } from "@/api";

export default {
  name: "Login",
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
        remember: false
      },
      errorMessage: "",
      isLoggingIn: false
    };
  },
  methods: {
    // 用户名/邮箱格式校验
    validateUsername(username) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return username.length > 0 && (emailRegex.test(username) || username.length >= 3);
    },
    
    // 密码长度校验
    validatePassword(password) {
      return password.length >= 6;
    },
    
    async handleLogin() {
      // 重置错误消息
      this.errorMessage = "";
      // 设置登录状态
      this.isLoggingIn = true;
      
      try {
        // 表单验证
        if (!this.validateUsername(this.loginForm.username)) {
          this.errorMessage = "请输入有效的用户名或邮箱";
          this.isLoggingIn = false;
          return;
        }
        
        if (!this.validatePassword(this.loginForm.password)) {
          this.errorMessage = "密码长度至少6位";
          this.isLoggingIn = false;
          return;
        }
        
        const response = await login({
          username: this.loginForm.username,
          password: this.loginForm.password
        });
        
        // 登录成功
        if (response.token) {
          // 存储token到本地
          localStorage.setItem("token", response.token);
          localStorage.setItem("user", JSON.stringify(response.data.user));
          
          // 处理记住登录状态（7天有效）
          if (this.loginForm.remember) {
            // 设置7天后过期的时间戳
            const expireTime = new Date().getTime() + 7 * 24 * 60 * 60 * 1000;
            localStorage.setItem("tokenExpire", expireTime);
          } else {
            localStorage.removeItem("tokenExpire");
          }
          
          // 检查是否有重定向路径
          const redirect = this.$route.query.redirect || "/home";
          // 跳转到目标页面
          this.$router.push(redirect);
        } else {
          this.errorMessage = response.message || "登录失败，请检查用户名和密码";
        }
      } catch (error) {
        console.error("登录出错:", error);
        this.errorMessage = "登录失败，请稍后再试";
      } finally {
        // 重置登录状态
        this.isLoggingIn = false;
      }
    },
    
    handleForgotPassword() {
      // 跳转到密码重置页面
      this.$router.push("/forgot-password");
    },
    
    handleRegister() {
      // 跳转到注册页面
      this.$router.push("/register");
    }
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-card {
  width: 100%;
  max-width: 400px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(10px);
  overflow: hidden;
  animation: slideUp 0.6s ease-out;
}

.login-header {
  padding: 40px 40px 20px;
  text-align: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
  margin-bottom: 15px;
}

.logo-img {
  width: 50px;
  height: 50px;
}

.system-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.welcome-text {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;
}

.login-form {
  padding: 30px 40px;
}

.form-group {
  margin-bottom: 20px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-wrapper i {
  position: absolute;
  left: 15px;
  color: #999;
  font-size: 18px;
}

.login-input {
  width: 100%;
  padding: 15px 15px 15px 45px;
  border: 2px solid #e1e5e9;
  border-radius: 10px;
  font-size: 16px;
  transition: all 0.3s ease;
  box-sizing: border-box;
  background: #f8f9fa;
}

.login-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  background: white;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  font-size: 14px;
}

.remember-me {
  display: flex;
  align-items: center;
  gap: 8px;
}

.checkbox {
  width: 18px;
  height: 18px;
  accent-color: #667eea;
}

.checkbox-label {
  color: #666;
}

.forgot-password {
  color: #667eea;
  text-decoration: none;
  transition: color 0.3s ease;
}

.forgot-password:hover {
  color: #764ba2;
  text-decoration: underline;
}

.login-btn {
  width: 100%;
  padding: 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.login-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.login-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.divider {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.divider::before,
.divider::after {
  content: "";
  flex: 1;
  border-bottom: 1px solid #e1e5e9;
}

.divider-text {
  padding: 0 15px;
  color: #999;
  font-size: 14px;
}

.social-login {
  display: flex;
  gap: 15px;
  margin-bottom: 25px;
}

.social-btn {
  flex: 1;
  padding: 12px;
  border: 2px solid #e1e5e9;
  border-radius: 10px;
  background: white;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.social-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.social-btn.google {
  color: #db4437;
}

.social-btn.github {
  color: #333;
}

.register-link {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.register-link a {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s ease;
}

.register-link a:hover {
  color: #764ba2;
  text-decoration: underline;
}

.error-message {
  color: #e74c3c;
  text-align: center;
  margin-top: 15px;
  font-size: 14px;
  animation: shake 0.5s;
  padding: 10px;
  background: rgba(231, 76, 60, 0.1);
  border-radius: 8px;
}

/* 图标字体 */
.icon-user::before {
  content: "👤";
}

.icon-lock::before {
  content: "🔒";
}

.icon-google::before {
  content: "G";
  font-weight: bold;
}

.icon-github::before {
  content: "GitHub";
  font-size: 12px;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes shake {
  0%,
  100% {
    transform: translateX(0);
  }
  10%,
  30%,
  50%,
  70%,
  90% {
    transform: translateX(-5px);
  }
  20%,
  40%,
  60%,
  80% {
    transform: translateX(5px);
  }
}

/* 移动端优化 */
@media (max-width: 767px) {
  .login-card {
    margin: 10px;
    border-radius: 15px;
  }
  
  .login-header {
    padding: 30px 20px 15px;
  }
  
  .logo {
    gap: 10px;
  }
  
  .logo-img {
    width: 40px;
    height: 40px;
  }
  
  .system-title {
    font-size: 20px;
  }
  
  .welcome-text {
    font-size: 13px;
  }
  
  .login-form {
    padding: 20px;
  }
  
  .social-login {
    flex-direction: column;
    gap: 10px;
  }
}
</style>
